// package.json中添加 type:commonjs
const http = require('http');
const url = require('url');
const fs = require('fs');
const sharp = require('sharp');
const path = require('path');
const formidable = require('formidable');
const { exec } = require('child_process');

const MAX_SIZE = 10* 1024 * 1024;//10Mb

const tinypng = (file,quality=80) => {
    // 将文件保存后并压缩
    return new Promise((resolve, reject) => {
        const outputPath = path.join(__dirname, 'input.png');
        sharp(file.filepath)
            .toFile(outputPath, (err, info) => {
                if (err) {
                    res.statusCode = 500;
                    res.end('Internal Server Error');
                    return;
                }
                const command = `pngquant input.png --quality=${quality} -o output.png`;

                exec(command, (error, stdout, stderr) => {
                    if (error) {
                        reject('压缩失败')
                        return '压缩失败';
                    }
                    fs.readFile(path.join(__dirname, 'output.png'), (err, data) => {
                        if (err) {
                            reject('读取失败')
                            return '读取失败';
                        }
                        // 删除临时文件
                        resolve(data);
                        fs.unlinkSync(path.join(__dirname, 'input.png'));
                        fs.unlinkSync(path.join(__dirname, 'output.png'));
                    });
                });
            });
    })
    // 获取保存的图片

}

const server = http.createServer((req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
    const { pathname } = url.parse(req.url, true);
    if (pathname === '/tinypng') {
        // 获取请求体
        const form = new formidable.IncomingForm();
        form.parse(req, async (err, fields, files,quality) => {
            if (err) {
                res.statusCode = 500;
                res.end('Internal Server Error');
                return;
            }
            const file = files.files[0];
            const { size } = file;
            if (size > MAX_SIZE) {
                res.statusCode = 413;
                res.end(JSON.stringify({
                    msg: 'File size exceeds the limit',
                    code: 413
                }));
                return;
            }
            const { originalFilename } = file;
            const ext = path.extname(originalFilename);
            if (ext !== '.png') {
                res.statusCode = 400;
                res.end('Only support PNG file');
                return;
            }
            const qt= fields?.quality?.[0] || 80;
            const result = await tinypng(file,qt);
            res.setHeader('Content-Type', 'image/png');
            res.statusCode = 200;
            // 图片转base64
            const base64 = Buffer.from(result).toString('base64');
            res.end(JSON.stringify({
                pic: base64
            }));
        });
    } else {
        res.statusCode = 404;
        res.end('Not Found');
    }
});
server.listen(3000, '127.0.0.1', () => {
    console.log('Server is running at http://localhost:3000');
})